/*
XPTracker - Alternative Agile Tracking Tool
Copyright (C) 2006-2009  Stephen Starkey

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/
package org.xptracker.web;

import net.sourceforge.stripes.action.HandlesEvent;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import org.apache.commons.logging.LogFactory;
import org.xptracker.domain.Story;
import org.xptracker.domain.User;
import org.xptracker.persistence.PersistenceManager;

public class StoryBookmarkActionBean extends StandardActionBean {
  private String storyId;
  private static final String REMOVED_STATUS = "removed";
  private static final String ADDED_STATUS = "added";

  public String getStoryId() {
    return storyId;
  }

  public void setStoryId(String storyId) {
    this.storyId = storyId;
  }

  @HandlesEvent("Add")
  public Resolution addBookmark() {
    return modifyBookmark(new BookmarkModifier() {
      public void modify(User user, Story story) {
        user.addBookmark(story);
      }
    }, ADDED_STATUS, REMOVED_STATUS);
  }

  @HandlesEvent("Remove")
  public Resolution removeBookmark() {
    return modifyBookmark(new BookmarkModifier() {
      public void modify(User user, Story story) {
        user.removeBookmark(story);
      }
    }, REMOVED_STATUS, ADDED_STATUS);
  }

  private Resolution modifyBookmark(final BookmarkModifier modifier, final String successStatus, String failureStatus) {
    try {
      return persistenceManager.inTransaction(new PersistenceManager.UpdateHandler<Resolution>() {
        public Resolution doUpdate(PersistenceManager.UpdateReceiver receiver) {
          Story story = domain.loadEntity(Story.class, storyId);
          User user = getCurrentUser();
          modifier.modify(user, story);
          receiver.update(user);
          return new StreamingResolution("text/plain", successStatus);
        }
      });
    } catch(Exception e) {
      LogFactory.getLog(getClass()).error("Error setting bookmark to status '" + successStatus + "'", e);
      return new StreamingResolution("text/plain", failureStatus);
    }
  }

  private static interface BookmarkModifier {
    void modify(User user, Story story);
  }
}
